package org.txazo.blog.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.txazo.blog.dao.MemberLoginInfoDao;
import org.txazo.blog.vo.MemberLoginInfo;

import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.TriggersRemove;

/**
 * 用户登录信息数据访问实现
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-12
 */
@Repository("memberLoginInfoDao")
public class MemberLoginInfoDaoImpl implements MemberLoginInfoDao {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public boolean addMemberLoginInfo(MemberLoginInfo memberLoginInfo) {
		String sql = "insert into blog.MemberLoginInfo (memberId, emailAccount, cipherText, cipherKey, createTime, lastModTime) values (?, ?, ?, ?, ?, ?)";
		return namedParameterJdbcTemplate.getJdbcOperations().update(
				sql,
				new Object[] { memberLoginInfo.getMemberId(),
						memberLoginInfo.getEmailAccount(),
						memberLoginInfo.getCipherText(),
						memberLoginInfo.getCipherKey(),
						memberLoginInfo.getCreateTime(),
						memberLoginInfo.getLastModTime() }) == 1;
	}

	@Override
	@TriggersRemove(cacheName = "org.txazo.cache.MemberInfoCache", removeAll = true)
	public boolean updateMemberLoginInfo(MemberLoginInfo memberLoginInfo) {
		String sql = "update blog.MemberLoginInfo set (cipherText, cipherKey, lastModTime) =  (?, ?, ?) where memberId = ?";
		return namedParameterJdbcTemplate.getJdbcOperations().update(
				sql,
				new Object[] { memberLoginInfo.getCipherText(),
						memberLoginInfo.getCipherKey(),
						memberLoginInfo.getLastModTime(),
						memberLoginInfo.getMemberId() }) == 1;
	}

	@Override
	@Cacheable(cacheName = "org.txazo.cache.MemberInfoCache")
	public MemberLoginInfo getMemberLoginInfo(String emailAccount) {
		MemberLoginInfo memberLoginInfo = null;
		String sql = "select * from blog.MemberLoginInfo where emailAccount = ?";
		try {
			memberLoginInfo = namedParameterJdbcTemplate.getJdbcOperations()
					.queryForObject(
							sql,
							ParameterizedBeanPropertyRowMapper
									.newInstance(MemberLoginInfo.class),
							new Object[] { emailAccount });
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
		return memberLoginInfo;
	}

}
